package com.lx.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInteceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws ServletException, IOException {

        //获取请求路径
        String url = request.getRequestURI();

        //请求路径中有 login 字符串 , 放行
        if (url.indexOf("/login")>=0||url.indexOf("/toLogin")>=0) return true;
        if (url.indexOf("/adminLogin")>=0||url.indexOf("/toAdminLogin")>=0) return true;

        if (url.indexOf("/register")>=0||url.indexOf("/toRegister")>=0) return true;
        if (url.indexOf("/adminRegister")>=0||url.indexOf("/toAdminRegister")>=0) return true;

        //放行，验证码请求路径
        if (url.indexOf("/verificationCode.do") >=0) return true;

        if (url.indexOf("/messageList") >=0) return true;

        //获取session
        HttpSession session = request.getSession();

        //已登录, 放行
        if (session.getAttribute("user") != null) return true;
        if (session.getAttribute("admin") != null) return true;

        //其他情况跳转到首页

        request.setAttribute("msg","未登录!登录后访问");

        //请求转发到首页页面
        request.getRequestDispatcher("/toLogin").forward(request,response);
        return false;
    }
}
